home *** CD-ROM | disk | FTP | other *** search
- Path: druid.borland.com!usenet
- From: pete@borland.com (Pete Becker)
- Newsgroups: comp.lang.c
- Subject: Re: Fastest way to computer log(base2) of x?
- Date: 5 Feb 1996 23:35:21 GMT
- Organization: Borland International
- Message-ID: <4f647p$lc5@druid.borland.com>
- References: <4e61iu$p6e@villa.fc.net> <4e72il$dvl@ns.RezoNet.NET>
- NNTP-Posting-Host: pbecker.borland.com
- Mime-Version: 1.0
- Content-Type: Text/Plain; charset=ISO-8859-1
- X-Newsreader: WinVN 0.99.5
-
- In article <4e72il$dvl@ns.RezoNet.NET>, ray@ultimate-tech.com says...
- >
- >In referenced article, Avinash Chopde says...
- >>I am trying to find out what could be the fastest way to compute
- >>the position of the highest bit in any given integer -- basically, the
- >>logarithm to the base 2 of any number.
- >
- >I can't think of any way faster than a variation of:
- >
- >/* Returns the Bitnumber of the highest set bit in n.
- > Assumes an int is maximum 32-bits long.
- > Returns -1 if n == 0
- >
- > Log2Table is a table filled with the bit-number of the highest bit
- > of the numbers 0 through 15
- >*/
- >
- >int FindHighestBitNumber(unsigned int n)
- >{ int i;
- > static int Log2Table[16] =
- > {-1, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3};
- >
- > i = 0;
- > if (n > 0xFFFF)
- > {
- > n = (n >> 16) & 0xFFFF;
- > i = 16;
- > }
- > if (n > 0xFF)
- > {
- > n = n >> 8;
- > i += 8;
- > }
- > if (n > 0xF)
- > {
- > n = n >> 4;
- > i += 4;
- > }
- > return(Log2Table[n] + i);
- >}
- >
- >You could also use a union to extract the appropriate byte if speed is
- >a concern and shifting is slow on your machine.
- >
- >If you want more speed, then give a 256 entry Log2Table and remove the
- >last conditional.
-
- Still faster: use a table with INT_MAX entries and remove all of the
- conditionals. Why do the responses here assume that sacrificing speed for
- space savings is appropriate? The question asks for the fastest, not something
- that's reasonably fast but doesn't use much space.
-
-